<?php

namespace WhaleIot\mqtt\libs;


use RedisException;
use WhaleIot\mqtt\utils\Redis;

class RedisQueue
{
    /**
     * 注释:添加队列消息
     * 创建者:JSL
     * 时间:2023/06/29 029 下午 01:43
     * @param array $data
     * @param int $delay
     * @return false|int|\Redis
     * @throws RedisException
     */
    public static function send(array $data, int $delay = 0)
    {
        $config        = self::getConfig();
        $redis         = new Redis($config);
        $queue_waiting = '{redis-queue}-waiting';
        $now           = time();
        $package_str   = json_encode([
                                         'id'       => rand(),
                                         'time'     => $now,
                                         'delay'    => 0,
                                         'attempts' => 0,
                                         'queue'    => $config['queue'],
                                         'data'     => $data
                                     ]);
        if ($delay) {
            $queue_delay = '{redis-queue}-delayed';
            return $redis->zAdd($queue_delay, $now + $delay, $package_str);
        }
        return $redis->lPush($queue_waiting . $config['queue'], $package_str);
    }

    /**
     * 注释:获取redis配置参数
     * 创建者:JSL
     * 时间:2023/06/29 029 下午 01:59
     * @return array
     */
    public static function getConfig(): array
    {
        if (function_exists('getWhaleIotConfig') && getWhaleIotConfig('whale-iot')) {
            $config = getWhaleIotConfig('whale-iot.redis');
            return [
                'ip'      => $config['ip'] ?? '127.0.0.1',
                'port'    => $config['port'] ?? '6379',
                'auth'    => $config['auth'] ?? '',//鉴权信息
                'db'      => $config['db'] ?? 0,
                'timeout' => $config['timeout'] ?? 0,
                'queue'   => $config['queue'] ?? 'whale-iot/mqtt/publish',
            ];
        }
    }
}